const { query } = require('../../../lib/db');
const { authenticateToken } = require('../../../lib/auth');
const { validate, ticketCreateSchema } = require('../../../lib/validation');

async function handler(req, res) {
  try {
    switch (req.method) {
      case 'GET':
        return await getTickets(req, res);
      case 'POST':
        return await createTicket(req, res);
      default:
        return res.status(405).json({
          success: false,
          message: '方法不允许'
        });
    }
  } catch (error) {
    console.error('工单API错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

// 获取工单列表
async function getTickets(req, res) {
  const {
    page = 1,
    limit = 10,
    status,
    priority,
    keyword,
    category,
    assignee,
    dateFrom,
    dateTo,
    user_id,
    application_id,
    module_id,
    product_category_id,
    source_type,
    impact_scope,
    urgency,
    tag_names
  } = req.query;

  const offset = (parseInt(page) - 1) * parseInt(limit);
  
  // 构建查询条件
  let whereConditions = [];
  let queryParams = [];

  // 根据用户角色限制数据访问
  if (req.user.role === 'user') {
    whereConditions.push('t.user_id = ?');
    queryParams.push(req.user.id);
  } else if (req.user.role === 'support') {
    whereConditions.push('(t.support_staff_id = ? OR t.support_staff_id IS NULL)');
    queryParams.push(req.user.id);
  }

  if (status) {
    whereConditions.push('t.status = ?');
    queryParams.push(status);
  }

  if (priority) {
    whereConditions.push('t.priority = ?');
    queryParams.push(priority);
  }

  if (keyword) {
    whereConditions.push('(t.title LIKE ? OR t.description LIKE ? OR t.ticket_number LIKE ?)');
    const keywordPattern = `%${keyword}%`;
    queryParams.push(keywordPattern, keywordPattern, keywordPattern);
  }

  if (category) {
    whereConditions.push('t.category = ?');
    queryParams.push(category);
  }

  if (assignee) {
    whereConditions.push('s.name = ?');
    queryParams.push(assignee);
  }

  if (dateFrom) {
    whereConditions.push('DATE(t.created_at) >= ?');
    queryParams.push(dateFrom);
  }

  if (dateTo) {
    whereConditions.push('DATE(t.created_at) <= ?');
    queryParams.push(dateTo);
  }

  if (user_id && req.user.role !== 'user') {
    whereConditions.push('t.user_id = ?');
    queryParams.push(user_id);
  }

  if (application_id) {
    whereConditions.push('t.application_id = ?');
    queryParams.push(application_id);
  }

  if (module_id) {
    whereConditions.push('t.module_id = ?');
    queryParams.push(module_id);
  }

  if (product_category_id) {
    whereConditions.push('t.product_category_id = ?');
    queryParams.push(product_category_id);
  }

  if (source_type) {
    whereConditions.push('t.source_type = ?');
    queryParams.push(source_type);
  }

  if (impact_scope) {
    whereConditions.push('t.impact_scope = ?');
    queryParams.push(impact_scope);
  }

  if (urgency) {
    whereConditions.push('t.urgency = ?');
    queryParams.push(urgency);
  }

  if (tag_names) {
    const tagArray = tag_names.split(',').map(tag => tag.trim());
    const tagPlaceholders = tagArray.map(() => '?').join(',');
    whereConditions.push(`t.id IN (
      SELECT DISTINCT tt.ticket_id 
      FROM ticket_tags tt 
      JOIN tags tag ON tt.tag_id = tag.id 
      WHERE tag.name IN (${tagPlaceholders})
    )`);
    queryParams.push(...tagArray);
  }

  const whereClause = whereConditions.length > 0 ? `WHERE ${whereConditions.join(' AND ')}` : '';

  // 查询总数
  const countSql = `
    SELECT COUNT(DISTINCT t.id) as total 
    FROM tickets t
    LEFT JOIN users u ON t.user_id = u.id
    LEFT JOIN users s ON t.support_staff_id = s.id
    LEFT JOIN applications app ON t.application_id = app.id
    LEFT JOIN modules mod ON t.module_id = mod.id
    LEFT JOIN product_categories pc ON t.product_category_id = pc.id
    ${whereClause}
  `;
  const countResult = await query(countSql, queryParams);
  const total = countResult[0].total;

  // 查询数据
  const dataSql = `
    SELECT DISTINCT
      t.*,
      u.name as user_name,
      u.department as user_department,
      s.name as support_staff_name,
      s.department as support_department,
      app.name as application_name,
      app.code as application_code,
      mod.name as module_name,
      mod.code as module_code,
      pc.name as product_category_name,
      pc.code as product_category_code,
      GROUP_CONCAT(DISTINCT tag.name) as tag_names,
      GROUP_CONCAT(DISTINCT tag.color) as tag_colors
    FROM tickets t
    LEFT JOIN users u ON t.user_id = u.id
    LEFT JOIN users s ON t.support_staff_id = s.id
    LEFT JOIN applications app ON t.application_id = app.id
    LEFT JOIN modules mod ON t.module_id = mod.id
    LEFT JOIN product_categories pc ON t.product_category_id = pc.id
    LEFT JOIN ticket_tags tt ON t.id = tt.ticket_id
    LEFT JOIN tags tag ON tt.tag_id = tag.id
    ${whereClause}
    GROUP BY t.id
    ORDER BY t.created_at DESC
    LIMIT ? OFFSET ?
  `;
  
  const dataQueryParams = [...queryParams, parseInt(limit), offset];
  const tickets = await query(dataSql, dataQueryParams);

  res.status(200).json({
    success: true,
    data: {
      tickets,
      pagination: {
        page: parseInt(page),
        limit: parseInt(limit),
        total,
        pages: Math.ceil(total / parseInt(limit))
      }
    }
  });
}

// 创建工单
async function createTicket(req, res) {
  // 验证请求数据
  const validation = validate(ticketCreateSchema, req.body);
  if (!validation.isValid) {
    return res.status(400).json({
      success: false,
      message: '请求数据验证失败',
      errors: validation.errors
    });
  }

  const ticketData = validation.data;
  
  // 生成工单编号
  const ticketNumber = await generateTicketNumber();
  
  const insertSql = `
    INSERT INTO tickets (
      ticket_number, user_id, support_staff_id, title, description, 
      source_url, source_type, resolution, location, ci_info, 
      product, sub_product, application_id, module_id, product_category_id,
      incident_level, impact_scope, urgency, business_impact, workaround,
      ticket_type, priority, category, due_date, estimated_hours
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  `;

  const insertParams = [
    ticketNumber,
    req.user.id,
    ticketData.support_staff_id || null,
    ticketData.title,
    ticketData.description,
    ticketData.source_url || null,
    ticketData.source_type || 'web',
    ticketData.resolution || null,
    ticketData.location || null,
    ticketData.ci_info || null,
    ticketData.product || null,
    ticketData.sub_product || null,
    ticketData.application_id || null,
    ticketData.module_id || null,
    ticketData.product_category_id || null,
    ticketData.incident_level,
    ticketData.impact_scope || 'individual',
    ticketData.urgency || 'medium',
    ticketData.business_impact || null,
    ticketData.workaround || null,
    ticketData.ticket_type,
    ticketData.priority,
    ticketData.category || null,
    ticketData.due_date || null,
    ticketData.estimated_hours || null
  ];

  const result = await query(insertSql, insertParams);
  const ticketId = result.insertId;

  // 处理标签
  if (ticketData.tags && Array.isArray(ticketData.tags) && ticketData.tags.length > 0) {
    await handleTicketTags(ticketId, ticketData.tags);
  }

  // 查询创建的工单详情
  const createdTicket = await query(
    `SELECT 
      t.*,
      u.name as user_name,
      s.name as support_staff_name
    FROM tickets t
    LEFT JOIN users u ON t.user_id = u.id
    LEFT JOIN users s ON t.support_staff_id = s.id
    WHERE t.id = ?`,
    [result.insertId]
  );

  res.status(201).json({
    success: true,
    message: '工单创建成功',
    data: createdTicket[0]
  });
}

// 生成工单编号
async function generateTicketNumber() {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const datePrefix = `T${year}${month}${day}`;

  // 查询当天最后一个工单编号
  const lastTicket = await query(
    `SELECT ticket_number FROM tickets 
     WHERE ticket_number LIKE ? 
     ORDER BY ticket_number DESC 
     LIMIT 1`,
    [`${datePrefix}%`]
  );

  let nextNumber = 1;
  if (lastTicket.length > 0) {
    const lastNumber = lastTicket[0].ticket_number.substring(9);
    nextNumber = parseInt(lastNumber) + 1;
  }

  return `${datePrefix}${String(nextNumber).padStart(3, '0')}`;
}

// 处理工单标签
async function handleTicketTags(ticketId, tagNames) {
  for (const tagName of tagNames) {
    if (!tagName || tagName.trim() === '') continue;
    
    const trimmedTagName = tagName.trim();
    
    // 查找或创建标签
    let tag = await query('SELECT id FROM tags WHERE name = ?', [trimmedTagName]);
    
    if (tag.length === 0) {
      // 创建新标签
      const insertTagResult = await query(
        'INSERT INTO tags (name, color) VALUES (?, ?)',
        [trimmedTagName, '#007bff']
      );
      tag = [{ id: insertTagResult.insertId }];
    }
    
    // 创建工单标签关联
    await query(
      'INSERT IGNORE INTO ticket_tags (ticket_id, tag_id) VALUES (?, ?)',
      [ticketId, tag[0].id]
    );
    
    // 更新标签使用次数
    await query(
      'UPDATE tags SET usage_count = usage_count + 1 WHERE id = ?',
      [tag[0].id]
    );
  }
}

export default authenticateToken(handler);